package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Modifier;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private MiniMapper mapper = new MiniMapper();



    //注意： 新代码全部加入 mini
    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
//        loadServlet();

        //加载miniServer
        loadServerXml();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/



        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap,mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }


    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();



    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    /**
     * 加载解析server.xml
     */
    private void loadServerXml() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//Server");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element serverElement =  selectNodes.get(i);
                List<Element> serviceList = serverElement.selectNodes("//Service");
                for (Element element : serviceList) {
                    Element connectorElement = (Element) element.selectSingleNode("Connector");
                    String port1 = connectorElement.attributeValue("port");
                    port = Integer.valueOf(port1);
                    List<Element> engineList = connectorElement.selectNodes("//Engine");
                    for (Element element1 : engineList) {
                        List<Element> hostList = element1.selectNodes("//Host");
                        for (Element element2 : hostList) {
                            //读取到appBase路径
                            String appBase = element2.attributeValue("appBase");
                            String name = element2.attributeValue("name");
                            MiniHost host = new MiniHost();
                            host.setAppBase(appBase);
                            host.setName(name);
                            mapper.getHosts().add(host);
                        }
                    }
                }
            }
//
//            //根据appBase路劲去扫描该路径下的包及servlet,封装相关对象
//            BuildMapper.buildMapper(mapper,servletMap);
              loadMiniMapper();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadMiniMapper(){
        List<MiniHost> hosts = mapper.getHosts();
        for (MiniHost host : hosts) {
            buildFile(host, host.getAppBase(), true);
        }
    }

    private void buildFile(MiniHost host, String packageName,  boolean flag ){
        String packagePath = packageName.replaceAll("\\.", "/");
        File fileInfo = new File(packagePath);
        File[] files = fileInfo.listFiles();
        for (File file : files) {
            if (file.getName().startsWith(".")){
                continue;
            }
            if (file.isDirectory()) {
                //如果是根目录下，封装Context
                if (flag) {
                    //获取webapp根目录下的文件夹名
                    String name = file.getName();
                    MiniContext context = new MiniContext();
                    context.setName(name);
                    host.getMiniContexts().add(context);
                }
                // 子package
                // 递归
                buildFile(host, packageName + "." + file.getName(), false);
            } else if (file.getName().endsWith(".class")) {
                for (MiniContext context : host.getMiniContexts()) {
                    //根据context的name分割路径包
                    String[] contextInfo = packagePath.split(context.getName() + "/");
                    if(contextInfo != null && contextInfo.length > 1){
                        try {
                            MiniWrapper wrapper = new MiniWrapper();
                            //只用类的名称，如LagouServlet
                            String classNameStr = file.getName().replaceAll(".class", "");
                            MiniClassLoader classLoader = new MiniClassLoader(file.getAbsolutePath());
                            Class<?> c = classLoader.findClass(contextInfo[1] + "." + classNameStr);
                            //判断某个类是否是HttpServlet子类，且不是抽象类
                            if(HttpServlet.class.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())){
                                HttpServlet o = (HttpServlet)c.newInstance();
                                String servletUrl = lowerFirst(classNameStr.split("Servlet")[0]);
                                //将以例如/demo1/lagou的访问路径放到映射对象中
//                                servletMap.put("/" + context.getName() + "/" + servletUrl, o);
                                //以自定义servlet前的单词为key存入wrapper的map中，如LagouServlet,就以lagou为key
                                wrapper.getMapperServlet().put("/" + context.getName() + "/" + servletUrl,o);
                                context.getMiniWrappers().add(wrapper);
                            }
                            System.out.println(11);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }


    private static String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
